package com.example.oop.ChatRoom;

import com.example.oop.POJO.Chat;
import com.example.oop.POJO.ChatRoom;
import com.example.oop.Repository.ChatRepository;
import com.example.oop.Repository.ChatRoomRepository;
import com.example.oop.Repository.RepositoryManager;
import org.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

//用于对聊天室进行管理
@Transactional
public class ChatRoomManager {
    // 全局唯一实例
    public static ChatRoomManager i = new ChatRoomManager();

    // 获取仓库
    private final ChatRoomRepository chatRoomRepository;
    private final ChatRepository chatRepository;

    // 单例设计 , 将构造方法设为私有
    private ChatRoomManager() {
        chatRoomRepository = RepositoryManager.chatRoomRepository;
        chatRepository = RepositoryManager.chatRepository;
    }

    // 登录时创建一个会话
    public ChatRoom createChatRoom(String username) {
        synchronized (this) {
            if (chatRoomRepository.findByUsername(username).isPresent()) {
//                用户上次异常退出
                ChatRoom chatRoom = chatRoomRepository.findByUsername(username).get();
//                chatRepository.deleteBySendChatRoom(chatRoom);  //数据删除异常
                return chatRoom;
            }

            int max = 0;
            //获取最后大的id
            List<ChatRoom> chatRoomList = chatRoomRepository.findAll();
            for (ChatRoom chatRoom : chatRoomList) {
                if (chatRoom.getId() > max) max = chatRoom.getId();
            }

            ChatRoom chatRoom = new ChatRoom(max + 1, username);
            chatRoomRepository.save(chatRoom);
            return chatRoom;
        }
    }

    // 发送一条消息
    public void sendMessage(JSONObject msg) {
        synchronized (this) {
            Chat chat = new Chat(
                    0,
                    new Date(),
                    msg.optString("content"),
                    chatRoomRepository.findByUsername(msg.optString("from")).get(),
                    chatRoomRepository.findByUsername(msg.optString("to")).get()
            );
            if (chat.getContent().equals("") || chat.getContent() == null) return;
            chatRepository.save(chat);
        }
    }

    // 存入消息
    public List<Chat> getMessage(JSONObject msg) {
//        使用互斥方式，避免进程同时访问
        synchronized (this) {
            List<Chat> list1 = null;
            try {
                list1 = chatRepository.findBySendChatRoomAndReceiveChatRoomOrderByChatTime(
                        chatRoomRepository.findByUsername(msg.optString("from")).get(),
                        chatRoomRepository.findByUsername(msg.optString("to")).get()
                );
                List<Chat> list2 = chatRepository.findBySendChatRoomAndReceiveChatRoomOrderByChatTime(
                        chatRoomRepository.findByUsername(msg.optString("to")).get(),
                        chatRoomRepository.findByUsername(msg.optString("from")).get()
                );
                for (Chat chat : list2) {
                    list1.add(chat);
                }
//            按照时间进行排序
                Collections.sort(list1, new Comparator<Chat>() {

                    @Override
                    public int compare(Chat o1, Chat o2) {
                        int flag = o1.getChatTime().compareTo(o2.getChatTime());
                        return flag;
                    }
                });
            } catch (Exception e) {

            }
            return list1;
        }
    }

    // 注销一个会话(级联删除关联的消息)
    public void deleteChatRoom(int chatRoomId) {
        synchronized (this) {
            chatRoomRepository.deleteById(chatRoomId);
        }
    }
}
